# -*- coding: utf-8 -*-

import ClientCookie
import sched
import time

s = sched.scheduler(time.time, time.sleep)

url = 'http://www.zjetc.net'

cj = ClientCookie.MSIECookieJar(delayload=True)
cj.load_from_registry()
opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
ClientCookie.install_opener(opener)

def main():
  global url

  res = ClientCookie.urlopen(url)
  html = res.read()
  res.close()

  print time.strftime('%Y-%m-%d %X :', time.localtime(time.time())),

  if html:
    content = unicode(html, 'utf-8')                # 不转成unicode就无法用find查找unicode
    i = content.find(u'还有')                     # '还有'后面那个数字就是红包数目
    if i < 0:
      print '无法获取cookie，请确保IE能直接登录论坛，并关闭IE！'
      exit()
    elif content[i+2] != '0':
      print '有红包。',

      i = html.find('formhash=')
      formhash = html[i:i+17]                     # formhash信息
      data = formhash + '&hid=2&hsubject=&money_get=%C1%EC%C8%A1%B8%C3%BA%EC%B0%FC'
      res = ClientCookie.urlopen(url[:-6], data)  # 不需要'&hid=2'

      html = res.read()
      content = unicode(html, 'gbk')
      i = content.find(u'领取了')
      if i < 0:
        print '无法领取，可能是你今天的红包已经领过了。'
      else:
        money = content[i+3:i+5].isdigit() and content[i+3:i+5] or content[i+3:i+4]
        print u'领取了%s金币。' % money
      exit()
    else:
      print '没有红包。'

  else:
    print '连接失败，请检查网络连接！'

  s.enter(60, 1, main, ())                       # 每60秒查询一次
  s.run()

if __name__ == "__main__":
  main()